package com.zbkj.service.manager.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zbkj.dal.base.constants.OrderConstants;
import com.zbkj.dal.base.enums.*;
import com.zbkj.dal.common.exception.CrmebException;
import com.zbkj.dal.common.utils.CrmebUtil;
import com.zbkj.dal.dao.*;
import com.zbkj.dal.entity.ba.Share;
import com.zbkj.dal.entity.merchant.Merchant;
import com.zbkj.dal.entity.order.Order;
import com.zbkj.dal.entity.profit.ShareProfitRecord;
import com.zbkj.dal.entity.profit.ShareProfitRole;
import com.zbkj.dal.entity.user.User;
import com.zbkj.dal.feign.client.WeWorkFeignClient;
import com.zbkj.service.manager.FundManager;
import com.zbkj.service.manager.ShareProfitManager;
import com.zbkj.service.manager.UserManager;
import com.zbkj.service.model.dto.FundUpdateDTO;
import com.zbkj.service.model.dto.PayeeMessageDTO;
import com.zbkj.service.model.dto.PayeeQueryDTO;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Slf4j
@Component
@AllArgsConstructor
public class ShareProfitManagerImpl implements ShareProfitManager {

    @Resource
    private OrderDao orderDao;

    @Resource
    private UserManager userManager;

    @Resource
    private FundManager fundManager;

    @Resource
    private MerchantDao merchantDao;

    @Resource
    private ShareMapper shareMapper;

    @Resource
    private WeWorkFeignClient weWorkFeignClient;

    @Resource
    private ShareProfitRoleDao shareProfitRoleDao;

    @Resource
    private TransactionTemplate transactionTemplate;

    @Resource
    private ShareProfitRecordDao shareProfitRecordDao;

    private static final Map<String, Function<PayeeQueryDTO, PayeeMessageDTO>> PAYEE_CODE_FUNCTION_MAP = new HashMap<>();

    @PostConstruct
    public void init() {
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.DIRECT_REFERRER.getCode(), this::directReferrerPayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.INDIRECT_REFERRER.getCode(), this::indirectReferrerPayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.PRODUCT_OWNER.getCode(), this::productOwnerPayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.MEMBER_BIND_MERCHANT.getCode(), this::memberBindStorePayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.MEMBER_BIND_MERCHANT_MANAGER.getCode(), this::memberBindStoreManagerPayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.SERVICE_MERCHANT.getCode(), this::serviceStorePayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.SERVICE_MERCHANT_MANAGER.getCode(), this::serviceStoreManagerPayeeCode);
        PAYEE_CODE_FUNCTION_MAP.put(SharePartyEnums.SHAN_XIE.getCode(), this::shanXiePayeeCode);
    }

    @Async
    @Override
    public void shareProfitInitAndConfirm(Integer userId, String bizOrderNo, String imagePath, BigDecimal baseAmount, BigDecimal shareAmount, ShareProfitSceneEnums shareProfitScene) {
        this.shareProfitInit(userId, bizOrderNo, imagePath, baseAmount, shareAmount, shareProfitScene);
        this.shareProfitConfirm(bizOrderNo);
    }

    @Async
    @Override
    public void shareProfitInitAsync(Integer userId, String bizOrderNo, String imagePath, BigDecimal orderAmount, BigDecimal shareAmount, ShareProfitSceneEnums shareProfitScene) {
        this.shareProfitInit(userId, bizOrderNo, imagePath, orderAmount, shareAmount, shareProfitScene);
    }

    public void shareProfitInit(Integer userId, String bizOrderNo, String imagePath, BigDecimal orderAmount, BigDecimal shareAmount, ShareProfitSceneEnums shareProfitScene) {
        transactionTemplate.execute(e -> {
            User user = userManager.findByUserId(userId);

            List<ShareProfitRecord> shareProfitRecordList = this.shareProfitRecords(bizOrderNo);
            if (CollectionUtil.isNotEmpty(shareProfitRecordList)) {
                log.error("业务单号：{}已初始化分润", bizOrderNo);
                return true;
            }

            // 查询规则
            LambdaQueryWrapper<ShareProfitRole> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShareProfitRole::getSceneCode, shareProfitScene.getCode());
            wrapper.eq(ShareProfitRole::getEnable, BooleanEnums.TRUE.getCode());
            wrapper.eq(ShareProfitRole::getDeleted, BooleanEnums.FALSE.getCode());
            List<ShareProfitRole> shareProfitRoles = shareProfitRoleDao.selectList(wrapper);

            List<ShareProfitRecord> shareProfitRecords = new ArrayList<>();
            for (ShareProfitRole role : shareProfitRoles) {
                Function<PayeeQueryDTO, PayeeMessageDTO> payeeCodeFunction = PAYEE_CODE_FUNCTION_MAP.get(role.getShareParty());
                if (Objects.isNull(payeeCodeFunction)) {
                    weWorkFeignClient.sendMessage(String.format("业务单：%s分润异常，未知用户身份：%s", bizOrderNo, role.getShareParty()));
                    log.error("业务单：{}分润异常，未知用户身份：{}", bizOrderNo, role.getShareParty());
                    continue;
                }
                PayeeMessageDTO payeeMessageDTO = payeeCodeFunction.apply(PayeeQueryDTO.generate(user, bizOrderNo, shareProfitScene.getCode()));
                String payeeCode = payeeMessageDTO.getPayeeCode();
                if (StringUtils.isNotBlank(payeeCode)) {
                    shareProfitRecords.add(generateShareProfitRecord(user, bizOrderNo, imagePath, payeeCode, orderAmount, shareAmount, null, role));
                } else {
                    String remark = String.format("分润方%s账户异常%s，金额分润给贝贝奢护", role.getShareParty(), payeeMessageDTO.getMessage());
                    PayeeMessageDTO shanXiePayee = shanXiePayeeCode(PayeeQueryDTO.generate(user, bizOrderNo, shareProfitScene.getCode()));
                    ShareProfitRecord shareProfitRecord = generateShareProfitRecord(user, bizOrderNo, imagePath, shanXiePayee.getPayeeCode(), orderAmount, shareAmount, remark, role);
                    shareProfitRecord.setPayeeType(SharePayeeTypeEnums.PLATFORM.name());
                    shareProfitRecords.add(shareProfitRecord);
                }
            }

            // 如果最后有剩余的，记录分给贝贝奢护
            BigDecimal amount = shareProfitRecords.stream().map(ShareProfitRecord::getRealAmount).reduce(BigDecimal.ZERO, BigDecimal::add);
            if (amount.compareTo(shareAmount) != 0) {
                BigDecimal residualAmount = shareAmount.subtract(amount);
                ShareProfitRecord shareProfitRecord = new ShareProfitRecord();
                shareProfitRecord.setShareProfitNo(CrmebUtil.getOrderNo(OrderConstants.CRAB_ROE_ACCOUNT_PREFIX));
                shareProfitRecord.setPayeeCode(SharePartyEnums.SHAN_XIE.getCode());
                shareProfitRecord.setPayeeType(SharePayeeTypeEnums.PLATFORM.name());
                shareProfitRecord.setSourceUserId(user.getId());
                shareProfitRecord.setSourceUserName(user.getNickname());
                shareProfitRecord.setShareParty(SharePartyEnums.SHAN_XIE.getCode());
                shareProfitRecord.setImagePath(imagePath);
                shareProfitRecord.setSceneCode(shareProfitScene.getCode());
                shareProfitRecord.setBillDate(LocalDate.now());
                shareProfitRecord.setBizOrderNo(bizOrderNo);
                shareProfitRecord.setShareModel(ShareModelEnums.FIXED.getCode());
                shareProfitRecord.setOrderAmount(orderAmount);
                shareProfitRecord.setShareAmount(shareAmount);
                shareProfitRecord.setRoleAmount(residualAmount);
                shareProfitRecord.setRealAmount(residualAmount);
                shareProfitRecord.setShareStatus(ShareSettleStatusEnums.WAIT_SETTLE.getCode());
                shareProfitRecord.setRemark(String.format("分润剩余%s，分给贝贝奢护", residualAmount));
                shareProfitRecord.setCreateTime(LocalDateTime.now());
                shareProfitRecord.setDeleted(BooleanEnums.FALSE.getCode());
                shareProfitRecords.add(shareProfitRecord);
            }

            shareProfitRecordDao.batchInsert(shareProfitRecords);

            // 雅识添加申请
            for (ShareProfitRecord shareProfitRecord : shareProfitRecords) {
                // 店铺、贝贝奢护目前不进行任何操作,只记录信息
                if (Objects.equals(SharePayeeTypeEnums.USER.name(), shareProfitRecord.getPayeeType()) && shareProfitRecord.getRealAmount().compareTo(BigDecimal.ZERO) != 0) {
                    fundManager.addCrabRoeApply(FundUpdateDTO.generateShareProfit(shareProfitRecord));
                }
            }
            return true;
        });
    }

    @Override
    public void shareProfitConfirmAsync(String bizOrderNo) {
        this.shareProfitConfirm(bizOrderNo);
    }

    public void shareProfitConfirm(String bizOrderNo) {
        transactionTemplate.execute(e -> {
            // 查询单据查询对应的分润记录
            List<ShareProfitRecord> shareProfitRecords = this.shareProfitRecords(bizOrderNo);
            if (!this.shareProfitConfirmCheck(bizOrderNo, shareProfitRecords)) {
                return true;
            }
            log.info("shareProfitRecords>>>{}", JSON.toJSONString(shareProfitRecords));
            for (ShareProfitRecord shareProfitRecord : shareProfitRecords) {
                // 店铺、贝贝奢护目前不进行任何操作,只记录信息

                if (!Objects.equals(SharePayeeTypeEnums.USER.name(), shareProfitRecord.getPayeeType())) {
                    continue;
                }
                log.info("shareProfitRecord>>>{}", JSON.toJSONString(shareProfitRecord));
                // 非初始化状态，不进行处理
                if (!(StringUtils.equals(shareProfitRecord.getShareStatus(), ShareSettleStatusEnums.WAIT_SETTLE.name()))) {
                    continue;
                }
                // 用户、店长添加雅识确认
                log.info("用户【{}】的分润记录确认，金额：{}", shareProfitRecord.getPayeeCode(), shareProfitRecord.getRealAmount());

                if (shareProfitRecord.getRealAmount().compareTo(BigDecimal.ZERO) != 0) {
                    fundManager.addCrabRoeConfirm(shareProfitRecord.getShareProfitNo());
                    log.info("=================开始分润====================");

                    // 添加用户周记录中的奖励金额
                    userManager.addRecruitReward(Integer.valueOf(shareProfitRecord.getPayeeCode()), shareProfitRecord.getRealAmount());
                }
            }

            shareProfitRecordDao.updateStatusByNo(bizOrderNo, ShareSettleStatusEnums.SETTLED.name(), LocalDateTime.now());

            return true;
        });
    }

    @Override
    public boolean shareProfitConfirmCheck(String bizOrderNo, List<ShareProfitRecord> shareProfitRecords) {
        if (CollectionUtils.isEmpty(shareProfitRecords)) {
            log.error("未查询到【{}】对应的分润记录", bizOrderNo);
            weWorkFeignClient.sendMessage(String.format("未查询到【%s】对应的分润记录", bizOrderNo));
            return false;
        }

        // 除了待结算的，其他的不处理
        String shareStatus = shareProfitRecords.get(0).getShareStatus();
        log.info("shareStatus>>>>{}", shareStatus);
        if (StringUtils.equals(shareStatus, ShareSettleStatusEnums.CLOSED.getCode())) {
            log.info("=========分润关闭================");
            return false;
        }
        if (!ShareSettleStatusEnums.WAIT_SETTLE.getCode().equals(shareStatus)) {
            log.info("=========分润状态未结算================");
            weWorkFeignClient.sendMessage(String.format("分润失败，业务单号为：%s，分润状态为：%s", bizOrderNo, shareStatus));
            return false;
        }

        // 如果是拉新的，查询有没有已经拉成功的（同一个被推荐人）,如果有，预警，并取消确认
        if (StringUtils.equals(ShareProfitSceneEnums.RECRUIT.getCode(), shareProfitRecords.get(0).getSceneCode())) {
            List<Integer> ids = shareProfitRecords.stream().map(ShareProfitRecord::getId).collect(Collectors.toList());
            LambdaQueryWrapper<ShareProfitRecord> recruitWrapper = new LambdaQueryWrapper<>();
            recruitWrapper.eq(ShareProfitRecord::getSourceUserId, shareProfitRecords.get(0).getSourceUserId());
            recruitWrapper.notIn(ShareProfitRecord::getId, ids);
            List<ShareProfitRecord> recruitShareProfitRecords = shareProfitRecordDao.selectList(recruitWrapper);
            log.error("recruitShareProfitRecords>>{}", JSON.toJSONString(recruitShareProfitRecords));
            if (recruitShareProfitRecords.stream().anyMatch(record -> StringUtils.equals(ShareSettleStatusEnums.SETTLED.getCode(), record.getShareStatus()))) {
                log.error("当前用户已有被拉新分润成功记录，取消分润");
                //return false;
            }
            if (CollectionUtil.isNotEmpty(recruitShareProfitRecords)) {
                recruitShareProfitRecords.forEach(record -> {
                    // 只有用户，才需要取消
                    if (Objects.equals(record.getPayeeType(), SharePayeeTypeEnums.USER.name())) {
                        fundManager.addCrabRoeApplyCancel(record.getShareProfitNo());
                    }
                });
                List<Integer> shareProfitRecordIds = recruitShareProfitRecords.stream().map(ShareProfitRecord::getId).collect(Collectors.toList());
                shareProfitRecordDao.updateStatus(shareProfitRecordIds, ShareSettleStatusEnums.CLOSED.getCode());
            }
        }
        return true;
    }

    @Override
    public void shareProfitClose(String bizOrderNo) {
        transactionTemplate.execute(e -> {
            List<ShareProfitRecord> shareProfitRecords = this.shareProfitRecords(bizOrderNo);
            if (CollectionUtil.isEmpty(shareProfitRecords)) {
                log.error("业务单号：{}分润关闭，但是未查询到对应的分润记录", bizOrderNo);
                return true;
            }
            if (shareProfitRecords.stream().anyMatch(r -> Objects.equals(r.getShareStatus(), ShareSettleStatusEnums.SETTLING.getCode()) ||
                    Objects.equals(r.getShareStatus(), ShareSettleStatusEnums.SETTLED.getCode()) ||
                    Objects.equals(r.getShareStatus(), ShareSettleStatusEnums.RECALL.getCode()))) {
                log.error("业务单号：{}分润关闭，但是分润已执行", bizOrderNo);
                weWorkFeignClient.sendMessage(String.format("业务单号：%s分润关闭，但是分润已执行", bizOrderNo));
                return true;
            }
            if (shareProfitRecords.stream().allMatch(r -> Objects.equals(r.getShareStatus(), ShareSettleStatusEnums.CLOSED.getCode()))) {
                return true;
            }
            for (ShareProfitRecord shareProfitRecord : shareProfitRecords) {
                fundManager.addCrabRoeApplyCancel(shareProfitRecord.getShareProfitNo());
            }
            shareProfitRecordDao.updateStatusByNo(bizOrderNo, ShareSettleStatusEnums.CLOSED.name(), null);
            return true;
        });
    }

    private PayeeMessageDTO directReferrerPayeeCode(PayeeQueryDTO payeeQueryDTO) {
        User user = payeeQueryDTO.getUser();
        User directSpreadUser = userManager.directSpreadUser(user.getId());
        if (Objects.isNull(directSpreadUser)) {
            return PayeeMessageDTO.generateEx(String.format("用户%s直接推荐人%s信息异常", user.getId(), user.getSpreadUid()));
        }
        return userShareProfitMessage(directSpreadUser);
    }

    private PayeeMessageDTO indirectReferrerPayeeCode(PayeeQueryDTO payeeQueryDTO) {
        User user = payeeQueryDTO.getUser();
        User indirectSpreadUser = userManager.indirectSpreadUser(user.getId());
        if (Objects.isNull(indirectSpreadUser)) {
            User directSpreadUser = userManager.directSpreadUser(user.getId());
            return PayeeMessageDTO.generateEx(String.format("用户%s间接推荐人%s信息异常", user.getId(), Objects.nonNull(directSpreadUser) ? directSpreadUser.getSpreadUid() : 0));
        }
        return userShareProfitMessage(indirectSpreadUser);
    }

    private PayeeMessageDTO userShareProfitMessage(User user) {
        if (!user.getStatus() || user.getIsLogoff()) {
            return PayeeMessageDTO.generateEx(String.format("用户%s状态异常", user.getId()));
        }
        if (BooleanEnums.isFalse(user.getEnableShareProfit())) {
            return PayeeMessageDTO.generateEx(String.format("用户%s未开启分润权限", user.getId()));
        }
        return PayeeMessageDTO.generate(user.getId());
    }

    private PayeeMessageDTO productOwnerPayeeCode(PayeeQueryDTO payeeQueryDTO) {
        String bizOrderNo = payeeQueryDTO.getBizOrderNo();
        if (!Objects.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.PRODUCT_RECYCLE_SALE.getCode())) {
            return PayeeMessageDTO.generateEx("当前场景不支持货主分润");
        }
        // 现在商品供享都是保价模式的，物主都是贝贝奢护
        LambdaQueryWrapper<Share> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Share::getOrderNo, bizOrderNo);
        Share share = shareMapper.selectOne(wrapper);
        User user = userManager.findByUserId(share.getUid());
        if (Objects.isNull(user)) {
            return PayeeMessageDTO.generateEx(String.format("货主%s状态异常", share.getUid()));
        }
        if (BooleanEnums.isFalse(user.getEnableShareProfit())) {
            return PayeeMessageDTO.generateEx(String.format("货主%s未开启分润权限", share.getUid()));
        }
        return PayeeMessageDTO.generate(user.getId());
    }

    private PayeeMessageDTO memberBindStorePayeeCode(PayeeQueryDTO payeeQueryDTO) {
        User user = payeeQueryDTO.getUser();
        Merchant merchant = merchantDao.selectById(user.getSpreadMerchantId());
        if (Objects.isNull(merchant)) {
            return PayeeMessageDTO.generateEx(String.format("用户%s绑定店铺%s信息异常", user.getId(), user.getSpreadMerchantId()));
        }
        return this.merchantShareProfitMessage(merchant);
    }

    private PayeeMessageDTO memberBindStoreManagerPayeeCode(PayeeQueryDTO payeeQueryDTO) {
        User user = payeeQueryDTO.getUser();
        Merchant merchant = merchantDao.selectById(user.getSpreadMerchantId());
        if (Objects.isNull(merchant)) {
            return PayeeMessageDTO.generateEx(String.format("用户%s绑定店铺%s信息异常", user.getId(), user.getSpreadMerchantId()));
        }
        User storeManager = userManager.findByUserId(merchant.getManagerUid());
        if (Objects.isNull(storeManager)) {
            return PayeeMessageDTO.generateEx(String.format("店铺%s店长%s信息异常", merchant.getId(), merchant.getManagerUid()));
        }
        return this.userShareProfitMessage(storeManager);
    }


    private PayeeMessageDTO merchantShareProfitMessage(Merchant merchant) {
        if (merchant.getIsDel()) {
            return PayeeMessageDTO.generateEx(String.format("店铺%s状态异常", merchant.getId()));
        }
        if (BooleanEnums.isFalse(merchant.getEnableShareProfit())) {
            return PayeeMessageDTO.generateEx(String.format("店铺%s未开启分润权限", merchant.getId()));
        }
        return PayeeMessageDTO.generate(merchant.getId());
    }

    private PayeeMessageDTO serviceStorePayeeCode(PayeeQueryDTO payeeQueryDTO) {
        if (StringUtils.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.RECRUIT.getCode())
                || StringUtils.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.PRODUCT_RECYCLE_SALE.getCode())
                || StringUtils.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.PRODUCT_RECYCLE_COLLATERAL.getCode())) {
            return PayeeMessageDTO.generateEx(String.format("当前分润场景%s未配置服务店铺信息", payeeQueryDTO.getSceneCode()));
        }
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getOrderNo, payeeQueryDTO.getBizOrderNo());
        wrapper.last(" limit 1");
        Order order = orderDao.selectOne(wrapper);
        if (ObjectUtil.isNull(order)) {
            return null;
        }
        Merchant merchant = merchantDao.selectById(order.getMerId());
        if (Objects.isNull(merchant)) {
            return PayeeMessageDTO.generateEx(String.format("订单%s服务店铺%s信息异常", payeeQueryDTO.getBizOrderNo(), order.getMerId()));
        }
        return this.merchantShareProfitMessage(merchant);

    }

    private PayeeMessageDTO serviceStoreManagerPayeeCode(PayeeQueryDTO payeeQueryDTO) {
        if (StringUtils.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.RECRUIT.getCode())
                || StringUtils.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.PRODUCT_RECYCLE_SALE.getCode())
                || StringUtils.equals(payeeQueryDTO.getSceneCode(), ShareProfitSceneEnums.PRODUCT_RECYCLE_COLLATERAL.getCode())) {
            return PayeeMessageDTO.generateEx(String.format("当前分润场景%s未配置服务店铺信息", payeeQueryDTO.getSceneCode()));
        }
        LambdaQueryWrapper<Order> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Order::getOrderNo, payeeQueryDTO.getBizOrderNo());
        wrapper.last(" limit 1");
        Order order = orderDao.selectOne(wrapper);
        if (ObjectUtil.isNull(order)) {
            return null;
        }
        Merchant merchant = merchantDao.selectById(order.getMerId());
        if (Objects.isNull(merchant)) {
            return PayeeMessageDTO.generateEx(String.format("订单%s服务店铺%s信息异常", payeeQueryDTO.getBizOrderNo(), order.getMerId()));
        }
        User storeManager = userManager.findByUserId(merchant.getManagerUid());
        if (Objects.isNull(storeManager)) {
            return PayeeMessageDTO.generateEx(String.format("服务店铺%s店长%s信息异常", merchant.getId(), merchant.getManagerUid()));
        }
        return this.userShareProfitMessage(storeManager);

    }

    private PayeeMessageDTO shanXiePayeeCode(PayeeQueryDTO payeeQueryDTO) {
        return PayeeMessageDTO.generate(SharePartyEnums.SHAN_XIE.getCode(), null);
    }

    private ShareProfitRecord generateShareProfitRecord(User user, String bizOrderNo, String imagePath, String payeeCode, BigDecimal orderAmount, BigDecimal shareAmount, String remark, ShareProfitRole shareProfitRole) {
        ShareProfitRecord shareProfitRecord = new ShareProfitRecord();
        shareProfitRecord.setSourceUserId(user.getId());
        shareProfitRecord.setSourceUserName(user.getNickname());
        shareProfitRecord.setImagePath(imagePath);
        shareProfitRecord.setBillDate(LocalDate.now());
        shareProfitRecord.setOrderAmount(orderAmount);
        shareProfitRecord.setShareAmount(shareAmount);
        shareProfitRecord.setPayeeCode(payeeCode);
        shareProfitRecord.setShareProfitNo(CrmebUtil.getOrderNo(OrderConstants.SHARE_PROFIT_PREFIX));
        shareProfitRecord.setPayeeType(shareProfitRole.getPayeeType());
        shareProfitRecord.setShareParty(shareProfitRole.getShareParty());
        shareProfitRecord.setSceneCode(shareProfitRole.getSceneCode());
        shareProfitRecord.setBizOrderNo(bizOrderNo);
        shareProfitRecord.setShareModel(shareProfitRole.getShareModel());
        shareProfitRecord.setRoleAmount(shareProfitRole.getShareAmount());
        if (StringUtils.equals(shareProfitRole.getShareModel(), ShareModelEnums.FIXED.getCode())) {
            shareProfitRecord.setRealAmount(shareProfitRole.getShareAmount());
        } else if (StringUtils.equals(shareProfitRole.getShareModel(), ShareModelEnums.FRACTION.getCode())) {
            shareProfitRecord.setRealAmount(shareProfitRole.getShareAmount().multiply(orderAmount).setScale(2, RoundingMode.DOWN));
        } else {
            String errorMessage = String.format("未知处理类型：%s，单据id：%s，收款人编号：%s，baseAmount：%s，shareProfitRole：%s",
                    shareProfitRole.getShareModel(), bizOrderNo, payeeCode, orderAmount, JSONUtil.toJsonStr(shareProfitRole));
            log.error(errorMessage);
            throw new CrmebException(errorMessage);
        }
        shareProfitRecord.setShareStatus(ShareSettleStatusEnums.WAIT_SETTLE.name());
        shareProfitRecord.setRemark(remark);
        shareProfitRecord.setCreateTime(LocalDateTime.now());
        shareProfitRecord.setUpdateTime(LocalDateTime.now());
        shareProfitRecord.setDeleted(BooleanEnums.FALSE.getCode());
        return shareProfitRecord;
    }

    public List<ShareProfitRecord> shareProfitRecords(String bizOrderNo) {
        // 查询单据id对应的分润记录
        LambdaQueryWrapper<ShareProfitRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShareProfitRecord::getBizOrderNo, bizOrderNo);
        wrapper.eq(ShareProfitRecord::getDeleted, BooleanEnums.FALSE.getCode());
        return shareProfitRecordDao.selectList(wrapper);
    }
}
